#!/usr/bin/env bash
set -euo pipefail

function write_error {
	echo "error(1): $1" 2>&1
	exit 1
}

function guard_bin {
	builtin type -P "$1" &>/dev/null || write_error "Could not find '$1'; $2"
}

guard_bin git "please install the Git CLI from https://git-scm.com/"
guard_bin dotnet "please install the .NET SDK from https://dot.net/"

if [ `uname -o` = Msys ]; then
	guard_bin msbuild.exe "please run this from a Visual Studio developer shell"
else
	guard_bin mono "please install Mono from https://www.mono-project.com/"
fi

git submodule status | while read line; do
	if [ "$(echo $line | cut -b1)" == "-" ]; then
		pieces=( $line )
		git submodule update --init ${pieces[1]}
		echo ""
	fi
done

PUSHED=0

cleanup () {
	if [[ $PUSHED == 1 ]]; then
		popd >/dev/null
		PUSHED=0
	fi
}

trap cleanup EXIT ERR INT TERM

pushd $( cd "$(dirname "$0")" ; pwd -P ) >/dev/null
PUSHED=1

dotnet run --project tools/builder --no-launch-profile -- "$@"
